/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.report.statistics.riskanddanger;

import com.koron.common.bean.DepartmentTreeBean;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.KpiStatistics;
import com.koron.common.mapper.KpiStatisticsMapper;
import com.koron.common.web.Util;

import com.koron.purpose.domain.KPITemplate;
import com.koron.purpose.mapper.KPITemplateMapper;
import com.koron.report.bean.StatisticsBean;
import com.koron.report.management.StatisticsManagement;

import com.koron.report.mapper.statistics.PerformMancePlanRateStatisticsMapper;
import com.koron.report.statistics.StatisticsService;
import com.koron.risk.bean.CorpBean;
import com.koron.risk.mapper.CorpManagementMapper;
import com.koron.risk.service.api.CorpManagementService;
import com.koron.risk.service.api.GridNodeService;
import com.koron.system.domain.District;
import com.koron.system.domain.DistrictCorpRelation;
import com.koron.system.mapper.DistrictMapper;
import com.koron.system.service.api.DistrictService;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.swan.bean.MessageBean;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class PerformMancePlanRateStatisticsServiceImpl implements StatisticsService, InitializingBean {

    private final static  Logger logger= LoggerFactory.getLogger(PerformMancePlanRateStatisticsServiceImpl.class);

    @Autowired
    private StatisticsManagement statisticsManagement;

    @Autowired
    private Util util;

    @Autowired
    private CorpManagementService corpManagementService;

    @Autowired
    private GridNodeService gridNodeService;

    @Autowired
    private DistrictService districtService;

    private static String PLAN_REGULAR_KPITEMPLATE="0072";
    private static String ACTUAL_REGULAR_KPITEMPLATE="0073";
    private static String ACTUAL_IRREGULAR_KPITEMPLATE="0076";



    @Override
    public void afterPropertiesSet() throws Exception {
        Set<Object> handlers = statisticsManagement.getHandlers();
        handlers.add(this);
    }

    @Override
    public void statisticsMonth(int year, int month) {
        try{
            //设置好时间
            Calendar calendar=Calendar.getInstance();
            calendar.set(year, month-1,1,0,0,0);
            Date startTime=calendar.getTime();
            calendar.set(year, month,1,0,0,0);
            Date endTime=calendar.getTime();
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM");
            int dateType=1;
            //计算定期计划总数,所有统计层级
            countCheck(simpleDateFormat,dateType,1,startTime,endTime,PLAN_REGULAR_KPITEMPLATE);
            //计算实际执行计划总数,所有统计层级
            countCheck(simpleDateFormat,dateType,2,startTime,endTime,ACTUAL_REGULAR_KPITEMPLATE);
            //计算临时执行总数,所有统计层级
            countCheck(simpleDateFormat,dateType,3,startTime,endTime,ACTUAL_IRREGULAR_KPITEMPLATE);
            //计算检查计划执行率,所有统计层级
            countRate(dateType,startTime,endTime);
        }catch (Exception e){
            logger.error("检查计划执行率按月统计各项指标计算失败，失败原因为："+e.getMessage());
        }
    }

    @Override
    public void statisticsQuarter(int year, int quarter) {
        try{
            Calendar calendar=Calendar.getInstance();
            int month=0;
            switch (quarter){
                case 1:
                    break;
                case 2:
                    month=3;
                    break;
                case 3:
                    month=6;
                    break;
                case 4:
                    month=9;
                    break;
                default:
                    break;
            }
            calendar.set(year, month,1,0,0,0);
            Date startTime=calendar.getTime();
            calendar.set(year, month+2,1,0,0,0);
            Date endTime=calendar.getTime();
            int dateType=2;
            //计算定期计划总数,所有统计层级
            countCheck(null,dateType,1,startTime,endTime,PLAN_REGULAR_KPITEMPLATE);
            //计算实际执行计划总数,所有统计层级
            countCheck(null,dateType,2,startTime,endTime,ACTUAL_REGULAR_KPITEMPLATE);
            //计算临时执行总数,所有统计层级
            countCheck(null,dateType,3,startTime,endTime,ACTUAL_IRREGULAR_KPITEMPLATE);
            //计算检查计划执行率,所有统计层级
            countRate(dateType,startTime,endTime);
        }catch (Exception e){
            logger.error("检查计划执行率按季度统计各项指标计算失败，失败原因为："+e.getMessage());
        }
    }

    @Override
    public void statisticsYear(int year) {
        try{
            //设置好时间
            Calendar calendar=Calendar.getInstance();
            calendar.set(year, 0,1,0,0,0);
            Date startTime=calendar.getTime();
            calendar.set(year+1, 0,1,0,0,0);
            Date endTime=calendar.getTime();
            int dateType=3;
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy");
            //计算定期计划总数,所有统计层级
            countCheck(simpleDateFormat,dateType,1,startTime,endTime,PLAN_REGULAR_KPITEMPLATE);
            //计算实际执行计划总数,所有统计层级
            countCheck(simpleDateFormat,dateType,2,startTime,endTime,ACTUAL_REGULAR_KPITEMPLATE);
            //计算临时执行总数,所有统计层级
            countCheck(simpleDateFormat,dateType,3,startTime,endTime,ACTUAL_IRREGULAR_KPITEMPLATE);
            //计算检查计划执行率,所有统计层级
            countRate(dateType,startTime,endTime);
        }catch (Exception e){
            logger.error("检查计划执行率按年统计各项指标计算失败，失败原因为："+e.getMessage());
        }
    }

    /**
     * 执行该方法，计算所有与检查计划执行率线管指标,但不包含检查计划执行率统计指标相关,不分统计层级
     * @param dateType  日期类型，1代表是月份，2代表是季度，3代表是年
     * @param statisticsType 计算指标类型 1:代表指标库code为0073,定期检查计划总数,
     *                                     2:代表指标库code为0072,已完成检查计划总数,
     *                                     3:代表指标库code为0076,临时检查计划总数
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param kpiTemplateCode 指标库code
     */
    private void countCheck(SimpleDateFormat simpleDateFormat,Integer dateType,Integer statisticsType,Date startTime,Date endTime,String kpiTemplateCode){
        SessionFactory factory=null;
        try{
            factory=new SessionFactory();
            KpiStatisticsMapper statisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
            //根据类型获取时间值
            String dataValue=getDateValue(dateType,startTime);
            //先删除当前时间值下的所有关于定期检查计划总数的统计数据，不份统计层级
            Integer del=statisticsMapper.delete(kpiTemplateCode,dataValue,null);
            //计算统计层级为员工的
            countCheckByPerson(factory,simpleDateFormat,dateType,statisticsType,startTime,endTime,kpiTemplateCode);
            //计算统计层级为部门的
            countCheckByDeptOrGroup(factory,simpleDateFormat,dateType,statisticsType,2,startTime,endTime,kpiTemplateCode);
            //计算统计层级为水司的
            countCheckByCorp(factory,simpleDateFormat,dateType,statisticsType,startTime,endTime,kpiTemplateCode);
            //计算统计层级为片区的
            countCheckByDistrict(factory,simpleDateFormat,dateType,statisticsType,startTime,endTime,kpiTemplateCode);
            //计算统计层级为集团的
            countCheckByDeptOrGroup(factory,simpleDateFormat,dateType,statisticsType,1,startTime,endTime,kpiTemplateCode);
            factory.close();
        }catch (Exception e){
            if (null!=factory)
                factory.close(false);
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
        }
    }

    /**
     *执行该方法，计算检查计划执行率指标，指标code为0031
     * @param dateType 日期类型，1代表是月份，2代表是季度，3代表是年
     * @param startTime 统计的开始时间
     * @param endTime 统计的结束时间
     */
    private void countRate(Integer dateType,Date startTime,Date endTime){
        SessionFactory factory=null;
        try{
            factory=new SessionFactory();
            KpiStatisticsMapper statisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
            String kpiTemplateCode="0031";
            //根据类型获取时间值
            String dataValue=getDateValue(dateType,startTime);
            //先删除当前时间值下的所有关于定期检查计划总数的统计数据，不份统计层级
            Integer del=statisticsMapper.delete(kpiTemplateCode,dataValue,null);
            //计算统计层级为员工的检查计划执行率
            countPerfromPlanRateByPerson(factory,dateType,startTime,endTime);
            //计算统计层级为部门的检查计划执行率
            countPerfromPlanRateByDept(factory,dateType,startTime,endTime);
            //计算统计层级为水司的检查计划执行率
            countPerfromPlanRateByCorp(factory,dateType,startTime,endTime);
            //计算统计层级为片区的检查计划执行率
            countPerformancePlanRateByDistrict(factory,dateType,startTime,endTime);
            //计算统计层级为集团的检查计划执行率
            countPerformancePlanRateByGroup(factory,dateType,startTime,endTime);
            factory.close();
        }catch (Exception e){
            if (null!=factory)
                factory.close(false);
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
        }
    }

    /**
     * 设置kpi指标的通用数据值
     * @param template
     * @param type 日期类型，1代表是月份，2代表是季度，3代表是年
     * @param date 日期
     * @return
     */
    private KpiStatistics generateKpiStatistics(KPITemplate template,Integer type,Date date){
        KpiStatistics kpiStatistics=new KpiStatistics();
        kpiStatistics.setKpiId(template.getId());
        kpiStatistics.setKpiCode(template.getCode());
        kpiStatistics.setKpiName(template.getName());
        //判断如何设置日期，1代表是月份，2代表是季度，3代表是年
        kpiStatistics.setDateType(type);
        kpiStatistics.setDateValue(getDateValue(type,date));
        return  kpiStatistics;
    }

    /**
     *根据日期和日期类型，获取相应的日期字符串
     * 月份返回形如2020-02，季度返回2020-1，年返回2020
     * @param type 日期类型，1代表是月份，2代表是季度，3代表是年
     * @param date  日期
     * @return
     */
    private String getDateValue(Integer type,Date date){
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(date);
        int year=calendar.get(Calendar.YEAR);
        int month=calendar.get(Calendar.MONTH)+1;
        switch (type){
            case 1:
                return ""+year+"-"+(month<10?"0"+month:month);
            case 2:
                return ""+year+"-"+(month/3+1);
            case 3:
                return year+"";
            default:
                return "";
        }
    }

    /**
     * 统计层级为员工，可统计3个指标，都与检查计划执行率相关
     * @param dateType  日期类型，1代表是月份，2代表是季度，3代表是年
     * @param statisticsType 计算指标类型 1:代表指标库code为0073,定期检查计划总数,
     *                                     2:代表指标库code为0072,已完成检查计划总数,
     *                                     3:代表指标库code为0076,临时检查计划总数
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param kpiTemplateCode 指标库code
     */
    private void countCheckByPerson(SessionFactory factory,SimpleDateFormat simpleDateFormat,Integer dateType,Integer statisticsType,Date startTime,
                                    Date endTime,String kpiTemplateCode) throws Exception {
        KpiStatisticsMapper kpiStatisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
        KPITemplateMapper templateMapper=factory.getMapper(KPITemplateMapper.class);
        PerformMancePlanRateStatisticsMapper statisticsMapper=factory.getMapper(PerformMancePlanRateStatisticsMapper.class);
        //插入数据
        List<KpiStatistics> kpiStatisticsList=null;
        //获取指标库模板
        KPITemplate kpiTemplate=templateMapper.queryTemplateByCode(kpiTemplateCode);
        //先统计
        List<StatisticsBean> list=new ArrayList<>();
        switch (statisticsType){
            case 1:
                list=statisticsMapper.countPlanRegularCheckStatisticsByPerson(startTime,endTime);
                break;
            case 2:
                list=statisticsMapper.countActualRegularCheckStatisticsByPerson(startTime,endTime);
                break;
            case 3:
                list=statisticsMapper.countActualIRRegularCheckStatisticsByPerson(startTime,endTime);
                break;
            default:
                list=null;
                break;
        }

        if(null!=list&&list.size()>0){
            kpiStatisticsList=new ArrayList<>();
            Date date=new Date();
            for(StatisticsBean statisticsBean:list){
                //由于数据问题，在统计时没有办法取到人的姓名，在此之前需要根据员工code获取员工名称
                List<StaffBean> staffBeanList= (List<StaffBean>) util.staff(statisticsBean.getCode(),null).getData();
                //员工确实存在
                if (null!=staffBeanList&&staffBeanList.size()>0){
                    KpiStatistics kpiStatistics=generateKpiStatistics(kpiTemplate,dateType,startTime);
                    kpiStatistics.setKpiValue(Float.parseFloat(statisticsBean.getValue()));
                    kpiStatistics.setObjectId(statisticsBean.getCode());
                    kpiStatistics.setObjectName(staffBeanList.get(0).getName());
                    kpiStatistics.setStatisticalType(1);
                    kpiStatistics.setAddTime(date);
                    kpiStatisticsList.add(kpiStatistics);
                }
            }
        }
        //将获取的统计数据批量插入
        if(null!=kpiStatisticsList&&kpiStatisticsList.size()>0){
            Integer value=kpiStatisticsMapper.batchInsert(kpiStatisticsList);
            if(value<0){
                String a=dateType==2?getDateValue(dateType,startTime):simpleDateFormat.format(startTime)+"计算指标库code为"+kpiTemplateCode;
                throw new Exception(a+"，统计层级为员工失败");
            }
        }
    }

    /**
     * 统计层级为部门或者集团，可统计3个指标，都与检查计划执行率相关
     * @param dateType  日期类型，1代表是月份，2代表是季度，3代表是年
     * @param statisticsType 计算指标类型 1:代表指标库code为0073,定期检查计划总数,
     *                                     2:代表指标库code为0072,已完成检查计划总数,
     *                                     3:代表指标库code为0076,临时检查计划总数
     * @param deptType 统计层级，1:统计层级为集团，2：统计层级为部门
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param kpiTemplateCode 指标库code
     */
    private void countCheckByDeptOrGroup(SessionFactory factory,SimpleDateFormat simpleDateFormat,Integer dateType,Integer statisticsType,
                                         Integer deptType,Date startTime,Date endTime,String kpiTemplateCode) throws Exception {
        PerformMancePlanRateStatisticsMapper performMancePlanRateStatisticsMapper=factory.getMapper(PerformMancePlanRateStatisticsMapper.class);
        KpiStatisticsMapper statisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
        if(deptType!=1&&deptType!=2){
            logger.error("统计计划定期检查总数失败，参数区分统计层级为部门或集团不合法，1集团，2部门");
            return;
        }
        List<KpiStatistics> kpiStatisticsList=null;
        Date date=new Date();
        if(deptType==1){
            //计算集团数据
            //查询集团统计值
            Integer total=0;
            switch (statisticsType){
                case 1:
                    total=performMancePlanRateStatisticsMapper.countPlanRegularCheckStatisticsByDeptOrGroup(startTime,endTime,null);
                    break;
                case 2:
                    total=performMancePlanRateStatisticsMapper.countActualRegularCheckStatisticsByDeptOrGroup(startTime,endTime,null);
                    break;
                case 3:
                    total=performMancePlanRateStatisticsMapper.countActualIRRegularCheckStatisticsByDeptOrGroup(startTime,endTime,null);
                    break;
                default:
                    break;
            }
            kpiStatisticsList=new ArrayList<>();
            //获取当前统计指标实体类
            KPITemplate kpiTemplate=factory.getMapper(KPITemplateMapper.class).queryTemplateByCode(kpiTemplateCode);
            KpiStatistics kpiStatistics=generateKpiStatistics(kpiTemplate,dateType,startTime);
            kpiStatistics.setObjectId("c75d5edacbc042448dab01951208421b");
            kpiStatistics.setObjectName("粤海水资源");
            kpiStatistics.setKpiValue(Float.parseFloat(total.toString()));
            kpiStatistics.setStatisticalType(5);
            kpiStatistics.setAddTime(date);
            kpiStatisticsList.add(kpiStatistics);
        }else{
            //计算部门数据
            //先获取当前组织架构上所有的部门
            List<DepartmentTreeBean> departmentTreeBeanList= (List<DepartmentTreeBean>) util.depttree("c75d5edacbc042448dab01951208421b",1).getData();
            if (null==departmentTreeBeanList&&departmentTreeBeanList.size()<=0){
                return;
            }
            //获取当前标志为水司的部门（组织架构）
            List<CorpBean> corpBeanList=corpManagementService.corpBeanList();

            //将当前获取的所有部门排除当前为水司，以及当前集团的的code，先排除集团
            List<DepartmentTreeBean> departmentTreeBeanList1=null;
            departmentTreeBeanList1=departmentTreeBeanList.stream().filter(d->d.getOrgCode().equals("c75d5edacbc042448dab01951208421b")).collect(Collectors.toList());
            //再排除水司
            List<String> corpCodeList=corpBeanList.stream().map(CorpBean::getCorpCode).collect(Collectors.toList());
            List<DepartmentTreeBean> result=null;
            result=departmentTreeBeanList1.stream().filter(d->!(corpCodeList.contains(d.getDepartmentCode()))).collect(Collectors.toList());
            //循环查询每个部门下有多少个整改隐患
            kpiStatisticsList=new ArrayList<>();
            for(DepartmentTreeBean departmentTreeBean:result){
                //查询该部门下所有子部门以及所有网格
                MessageBean<?> msg=gridNodeService.childList(departmentTreeBean.getDepartmentCode(),1);
                //存储部门和网格code
                List<String> codeList=new ArrayList<>();
                if (msg.getData()!=null) {
                    List<Map<String,String>> mapList= (List<Map<String, String>>) msg.getData();
                    codeList=mapList.stream().map(m->m.get("code")).collect(Collectors.toList());
                }else{
                    codeList.add(departmentTreeBean.getDepartmentCode());
                }
                //查询统计值
                Integer total=0;
                if (codeList!=null&&codeList.size()>0){
                    switch (statisticsType){
                        case 1:
                            total=performMancePlanRateStatisticsMapper.countPlanRegularCheckStatisticsByDeptOrGroup(startTime,endTime,codeList);
                            break;
                        case 2:
                            total=performMancePlanRateStatisticsMapper.countActualRegularCheckStatisticsByDeptOrGroup(startTime,endTime,codeList);
                            break;
                        case 3:
                            total=performMancePlanRateStatisticsMapper.countActualIRRegularCheckStatisticsByDeptOrGroup(startTime,endTime,codeList);
                            break;
                        default:
                            break;
                    }
                }
                //查询出的数据取大于0的数据
                if (total>0){
                    //获取当前统计指标实体类
                    KPITemplate kpiTemplate=factory.getMapper(KPITemplateMapper.class).queryTemplateByCode(kpiTemplateCode);
                    KpiStatistics kpiStatistics=generateKpiStatistics(kpiTemplate,dateType,startTime);
                    kpiStatistics.setObjectId(departmentTreeBean.getDepartmentCode());
                    kpiStatistics.setObjectName(departmentTreeBean.getName());
                    kpiStatistics.setKpiValue(Float.parseFloat(total.toString()));
                    kpiStatistics.setStatisticalType(2);
                    kpiStatistics.setAddTime(date);
                    kpiStatisticsList.add(kpiStatistics);
                }
            }
        }
        //执行批量插入操作
        if (null!=kpiStatisticsList&&kpiStatisticsList.size()>0){
            Integer value=statisticsMapper.batchInsert(kpiStatisticsList);
            if(value<0){
                String a=dateType==2?getDateValue(dateType,startTime):simpleDateFormat.format(startTime);
                throw new Exception(a+"计算指标库code为"+kpiTemplateCode+
                        "，统计层级为"+(deptType==1?"集团":"部门")+"失败");
            }
        }
    }

    /**
     * 统计层级为水司，可统计3个指标，都与检查计划执行率相关
     * @param dateType  日期类型，1代表是月份，2代表是季度，3代表是年
     * @param statisticsType 计算指标类型 1:代表指标库code为0073,定期检查计划总数,
     *                                     2:代表指标库code为0072,已完成检查计划总数,
     *                                     3:代表指标库code为0076,临时检查计划总数
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param kpiTemplateCode 指标库code
     */
    private void countCheckByCorp(SessionFactory factory,SimpleDateFormat simpleDateFormat,Integer dateType,Integer statisticsType,Date startTime,
                                  Date endTime,String kpiTemplateCode) throws Exception {
        KpiStatisticsMapper kpiStatisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
        KPITemplateMapper templateMapper=factory.getMapper(KPITemplateMapper.class);
        PerformMancePlanRateStatisticsMapper statisticsMapper=factory.getMapper(PerformMancePlanRateStatisticsMapper.class);
        //插入数据
        List<KpiStatistics> kpiStatisticsList=null;
        //获取指标库模板
        KPITemplate kpiTemplate=templateMapper.queryTemplateByCode(kpiTemplateCode);
        //先统计
        List<StatisticsBean> list=new ArrayList<>();
        switch (statisticsType){
            case 1:
                list=statisticsMapper.countPlanRegularCheckStatisticsByCorp(startTime,endTime);
                break;
            case 2:
                list=statisticsMapper.countActualRegularCheckStatisticsByCorp(startTime,endTime);
                break;
            case 3:
                list=statisticsMapper.countActualIRRegularCheckStatisticsByCorp(startTime,endTime);
                break;
            default:
                list=null;
                break;
        }

        if(null!=list&&list.size()>0){
            kpiStatisticsList=new ArrayList<>();
            Date date=new Date();
            for(StatisticsBean statisticsBean:list){
                //由于数据问题，在统计时没有办法取到水司的名称，在此之前需要根据水司code获取水司的名称
                CorpBean corpBean=factory.getMapper(CorpManagementMapper.class).get(statisticsBean.getCode());
                //水司不存在，结束本次循环
                if (null==corpBean){
                    continue;
                }
                KpiStatistics kpiStatistics=generateKpiStatistics(kpiTemplate,dateType,startTime);
                kpiStatistics.setKpiValue(Float.parseFloat(statisticsBean.getValue()));
                kpiStatistics.setObjectId(statisticsBean.getCode());
                kpiStatistics.setObjectName(corpBean.getCorpName());
                kpiStatistics.setStatisticalType(3);
                kpiStatistics.setAddTime(date);
                kpiStatisticsList.add(kpiStatistics);
            }
        }
        //将获取的统计数据批量插入
        if(null!=kpiStatisticsList&&kpiStatisticsList.size()>0){
            Integer value=kpiStatisticsMapper.batchInsert(kpiStatisticsList);
            if(value<0){
                String a=dateType==2?getDateValue(dateType,startTime):simpleDateFormat.format(startTime);
                throw new Exception(a+"计算指标库code为"+kpiTemplateCode+
                        "，统计层级为水司失败");
            }
        }
    }

    /**
     * 统计层级为片区，可统计3个指标，都与检查计划执行率相关
     * @param dateType  日期类型，1代表是月份，2代表是季度，3代表是年
     * @param statisticsType 计算指标类型 1:代表指标库code为0073,定期检查计划总数,
     *                                     2:代表指标库code为0072,已完成检查计划总数,
     *                                     3:代表指标库code为0076,临时检查计划总数
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param kpiTemplateCode 指标库code
     */
    private void countCheckByDistrict(SessionFactory factory,SimpleDateFormat simpleDateFormat,Integer dateType,Integer statisticsType,Date startTime,Date endTime,String kpiTemplateCode) throws Exception {
        KpiStatisticsMapper kpiStatisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
        KPITemplateMapper templateMapper=factory.getMapper(KPITemplateMapper.class);
        PerformMancePlanRateStatisticsMapper performMancePlanRateStatisticsMapper=factory.getMapper(PerformMancePlanRateStatisticsMapper.class);
        DistrictMapper districtMapper=factory.getMapper(DistrictMapper.class);
        //插入数据
        List<KpiStatistics> kpiStatisticsList=null;
        //获取指标库模板
        KPITemplate kpiTemplate=templateMapper.queryTemplateByCode(kpiTemplateCode);
        //查询当前所有片区
        List<District> districtList=districtMapper.queryAllDistrict(null,null);
        if(null!=districtList&&districtList.size()>0){
            Date date=new Date();
            kpiStatisticsList=new ArrayList<>();
            for(District district:districtList){
                List<DistrictCorpRelation> relationList=districtService.queryDistrictCorp(district.getCode(),null,null).getData().getList();
                List<String> corpCodeList=relationList.stream().map(DistrictCorpRelation::getCorpCode).collect(Collectors.toList());
                if (null!=corpCodeList&&corpCodeList.size()>0){
                    Integer total=0;
                    switch (statisticsType){
                        case 1:
                            total=performMancePlanRateStatisticsMapper.countPlanRegularCheckStatisticsByDistrict(startTime,endTime,corpCodeList);
                            break;
                        case 2:
                            total=performMancePlanRateStatisticsMapper.countActualRegularCheckStatisticsByDistrict(startTime,endTime,corpCodeList);
                            break;
                        case 3:
                            total=performMancePlanRateStatisticsMapper.countActualIRRegularCheckStatisticsByDistrict(startTime,endTime,corpCodeList);
                            break;
                        default:
                            break;
                    }
                    //确保不为0的数据不插入到数据库中
                    if(total>0){
                        KpiStatistics kpiStatistics=generateKpiStatistics(kpiTemplate,dateType,startTime);
                        kpiStatistics.setObjectId(district.getCode());
                        kpiStatistics.setObjectName(district.getName());
                        kpiStatistics.setStatisticalType(3);
                        kpiStatistics.setAddTime(date);
                        kpiStatistics.setKpiValue(Float.parseFloat(total.toString()));
                        kpiStatisticsList.add(kpiStatistics);
                    }
                }
            }
        }
        if(null!=kpiStatisticsList&&kpiStatisticsList.size()>0){
            //执行批量插入操作
            Integer value=kpiStatisticsMapper.batchInsert(kpiStatisticsList);
            if(value<0){
                String a=dateType==2?getDateValue(dateType,startTime):simpleDateFormat.format(startTime);
                throw  new Exception(a+"计算指标库code为"+kpiTemplateCode+
                        "，统计层级为片区失败");
            }
        }
    }
    /**
     * 统计层级为员工，指标名称：检查计划完成率，指标code为0031
     * @param type 日期类型，1代表是月份，2代表是季度，3代表是年
     * @param startTime 统计的开始时间
     * @param endTime 统计的结束时间
     */
    private void countPerfromPlanRateByPerson(SessionFactory factory,Integer type,Date startTime,Date endTime) throws Exception {
        PerformMancePlanRateStatisticsMapper performMancePlanRateStatisticsMapper=factory.getMapper(PerformMancePlanRateStatisticsMapper.class);
        KPITemplateMapper templateMapper=factory.getMapper(KPITemplateMapper.class);
        KpiStatisticsMapper statisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
        KPITemplate kpiTemplate=templateMapper.queryTemplateByCode("0031");
        List<KpiStatistics> kpiStatisticsList=null;
        //查询计算检查计划完成率的其他指标的数据查询出来
        List<StatisticsBean> planRegularCheckList=performMancePlanRateStatisticsMapper.countPlanRegularCheckStatisticsByPerson(startTime, endTime);
        List<StatisticsBean> auctualRegularCheckList=performMancePlanRateStatisticsMapper.countActualRegularCheckStatisticsByPerson(startTime, endTime);
        List<StatisticsBean> acutalIrregularCheckList=performMancePlanRateStatisticsMapper.countActualIRRegularCheckStatisticsByPerson(startTime, endTime);
        //用来检测是否临时检查计划存在定期检查计划不存在的员工执行记录,
        //flag最后值与临时检查计划检查相等，即临时检查计划的员工记录与定期人员相匹配
        //flag最后值与临时检查计划检查相等，即临时检查计划的员工记录存在定期人员中没有的
        int flag=0;
        Date date=new Date();
        for(StatisticsBean statisticsBean:planRegularCheckList){
            if (null==kpiStatisticsList){
                kpiStatisticsList=new ArrayList<>();
            }
            //先判断是否有对应员工的临时检查计划
            List<StatisticsBean> tempIrregularList=acutalIrregularCheckList.stream().filter(s->s.getCode().equals(statisticsBean.getCode())).collect(Collectors.toList());
            //由于数据问题，在统计时没有办法取到人的姓名，在此之前需要根据员工code获取员工名称
            List<StaffBean> staffBeanList= (List<StaffBean>) util.staff(statisticsBean.getCode(),null).getData();
            //员工不存在，结束本次循环
            if (null==staffBeanList||staffBeanList.size()<=0){
                continue;
            }
            Float total=+Float.parseFloat(statisticsBean.getValue());
            if (null!=tempIrregularList&&tempIrregularList.size()>0){
                flag++;
                total=total+Float.parseFloat(tempIrregularList.get(0).getValue());
            }
            //确保分母不为0且大于0
            if (total>0){
                List<StatisticsBean> tempActualRegular=auctualRegularCheckList.stream().filter(s->s.getCode().equals(statisticsBean.getCode())).collect(Collectors.toList());
                Float result=0F;
                if (tempActualRegular!=null&&tempActualRegular.size()>0){
                    result=Float.parseFloat(tempActualRegular.get(0).getValue());
                }
                KpiStatistics kpiStatistics=generateKpiStatistics(kpiTemplate,type,startTime);
                kpiStatistics.setKpiValue(result/total);
                kpiStatistics.setObjectId(statisticsBean.getCode());
                kpiStatistics.setObjectName(staffBeanList.get(0).getName());
                kpiStatistics.setStatisticalType(1);
                kpiStatistics.setAddTime(date);
                kpiStatisticsList.add(kpiStatistics);
            }
        }
        //临时检查计划的员工记录存在定期人员中没有的
        if (flag<acutalIrregularCheckList.size()){
            if (null==kpiStatisticsList){
                kpiStatisticsList=new ArrayList<>();
            }
            //获取定期的人员code
            List<String> userCodeList=planRegularCheckList.stream().map(StatisticsBean::getCode).collect(Collectors.toList());
            for(StatisticsBean statisticsBean:acutalIrregularCheckList){
                if (!userCodeList.contains(statisticsBean.getCode())){
                    List<StaffBean> staffBeanList= (List<StaffBean>) util.staff(statisticsBean.getCode(),null).getData();
                    //员工不存在，结束本次循环
                    if (null==staffBeanList||staffBeanList.size()<=0){
                        continue;
                    }
                    List<StatisticsBean> tempActualRegular=auctualRegularCheckList.stream().filter(s->s.getCode().equals(statisticsBean.getCode())).collect(Collectors.toList());
                    KpiStatistics kpiStatistics=generateKpiStatistics(kpiTemplate,type,startTime);
                    kpiStatistics.setKpiValue(Float.parseFloat(tempActualRegular.get(0).getValue())/Float.parseFloat(statisticsBean.getValue()));
                    kpiStatistics.setObjectId(statisticsBean.getCode());
                    kpiStatistics.setObjectName(staffBeanList.get(0).getName());
                    kpiStatistics.setStatisticalType(1);
                    kpiStatistics.setAddTime(date);
                    kpiStatisticsList.add(kpiStatistics);
                }
            }
        }
        //执行批量插入操作
        if (null!=kpiStatisticsList&&kpiStatisticsList.size()>0){
            Integer value=statisticsMapper.batchInsert(kpiStatisticsList);
            if(value<0){
                SimpleDateFormat format=new SimpleDateFormat();
                String a=type==2?getDateValue(type,startTime):format.format(startTime);
                throw  new Exception(a+"计算指标库code为0031，统计层级为人员失败");
            }
        }

    }

    /**
     * 统计层级为部门，指标名称：检查计划完成率，指标code为0031
     * @param type 日期类型，1代表是月份，2代表是季度，3代表是年
     * @param startTime 统计的开始时间
     * @param endTime 统计的结束时间
     */
    private void countPerfromPlanRateByDept(SessionFactory factory,Integer type,Date startTime,Date endTime) throws Exception {
        PerformMancePlanRateStatisticsMapper performMancePlanRateStatisticsMapper=factory.getMapper(PerformMancePlanRateStatisticsMapper.class);
        KpiStatisticsMapper statisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
        KPITemplate kpiTemplate=factory.getMapper(KPITemplateMapper.class).queryTemplateByCode("0031");
        List<KpiStatistics> kpiStatisticsList=null;
        Date date=new Date();
        List<District> districtList=factory.getMapper(DistrictMapper.class).queryAllDistrict(null,null);
        List<DepartmentTreeBean> departmentTreeBeanList= (List<DepartmentTreeBean>) util.depttree("c75d5edacbc042448dab01951208421b",1).getData();
        if (null==departmentTreeBeanList&&departmentTreeBeanList.size()<=0){
            return;
        }
        //获取当前标志为水司的部门（组织架构）
        List<CorpBean> corpBeanList=corpManagementService.corpBeanList();

        //将当前获取的所有部门排除当前为水司，以及当前集团的的code,先排除集团
        List<DepartmentTreeBean> departmentTreeBeanList1=null;
        departmentTreeBeanList1=departmentTreeBeanList.stream().filter(d->d.getOrgCode().equals("c75d5edacbc042448dab01951208421b")).collect(Collectors.toList());
        //再排除水司
        List<String> corpCodeList=corpBeanList.stream().map(CorpBean::getCorpCode).collect(Collectors.toList());
        List<DepartmentTreeBean> result=null;
        result=departmentTreeBeanList1.stream().filter(d->!(corpCodeList.contains(d.getDepartmentCode()))).collect(Collectors.toList());
        //循环查询每个部门下有多少个整改隐患
        kpiStatisticsList=new ArrayList<>();
        for(DepartmentTreeBean departmentTreeBean:result){
            //查询该部门下所有子部门以及所有网格
            MessageBean<?> msg=gridNodeService.childList(departmentTreeBean.getDepartmentCode(),1);
            //存储部门和网格code
            List<String> codeList=new ArrayList<>();
            if (msg.getData()!=null) {
                List<Map<String,String>> mapList= (List<Map<String, String>>) msg.getData();
                codeList=mapList.stream().map(m->m.get("code")).collect(Collectors.toList());
            }else{
                codeList.add(departmentTreeBean.getDepartmentCode());
            }
            //查询统计值
            Integer plan=performMancePlanRateStatisticsMapper.countPlanRegularCheckStatisticsByDeptOrGroup(startTime,endTime,codeList);
            Integer actualRegular=performMancePlanRateStatisticsMapper.countPlanRegularCheckStatisticsByDeptOrGroup(startTime,endTime,codeList);
            Integer actualIrregular=performMancePlanRateStatisticsMapper.countActualIRRegularCheckStatisticsByDeptOrGroup(startTime,endTime,codeList);
            Float total=Float.parseFloat(plan.toString())+Float.parseFloat(actualIrregular.toString());
            //确保分母不为0
            if (total>0){
                KpiStatistics kpiStatistics=generateKpiStatistics(kpiTemplate,type,startTime);
                kpiStatistics.setObjectId(departmentTreeBean.getDepartmentCode());
                kpiStatistics.setObjectName(departmentTreeBean.getName());
                kpiStatistics.setKpiValue(Float.parseFloat(actualIrregular.toString())/Float.parseFloat(total.toString()));
                kpiStatistics.setStatisticalType(2);
                kpiStatistics.setAddTime(date);
                kpiStatisticsList.add(kpiStatistics);
            }

        }
        //执行批量插入操作
        if (null!=kpiStatisticsList&&kpiStatisticsList.size()>0){
            Integer value=statisticsMapper.batchInsert(kpiStatisticsList);
            if(value<0){
                SimpleDateFormat format=new SimpleDateFormat();
                String a=type==2?getDateValue(type,startTime):format.format(startTime);
                throw  new Exception(a+"计算指标库code为0031，统计层级为部门失败");
            }
        }
    }

    /**
     * 统计层级为水司，指标名称：检查计划完成率，指标code为0031
     * @param type 日期类型，1代表是月份，2代表是季度，3代表是年
     * @param startTime 统计的开始时间
     * @param endTime 统计的结束时间
     */
    private void countPerfromPlanRateByCorp(SessionFactory factory,Integer type,Date startTime,Date endTime) throws Exception {
        PerformMancePlanRateStatisticsMapper performMancePlanRateStatisticsMapper=factory.getMapper(PerformMancePlanRateStatisticsMapper.class);
        KPITemplateMapper templateMapper=factory.getMapper(KPITemplateMapper.class);
        KpiStatisticsMapper statisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
        KPITemplate kpiTemplate=templateMapper.queryTemplateByCode("0031");
        List<KpiStatistics> kpiStatisticsList=null;
        //查询计算检查计划完成率的其他指标的数据查询出来
        List<StatisticsBean> planRegularCheckList=performMancePlanRateStatisticsMapper.countPlanRegularCheckStatisticsByCorp(startTime, endTime);
        List<StatisticsBean> auctualRegularCheckList=performMancePlanRateStatisticsMapper.countActualRegularCheckStatisticsByCorp(startTime, endTime);
        List<StatisticsBean> acutalIrregularCheckList=performMancePlanRateStatisticsMapper.countActualIRRegularCheckStatisticsByCorp(startTime, endTime);
        //用来检测是否临时检查计划存在定期检查计划不存在的员工执行记录,
        //flag最后值与临时检查计划检查相等，即临时检查计划的员工记录与定期人员相匹配
        //flag最后值与临时检查计划检查相等，即临时检查计划的员工记录存在定期人员中没有的
        int flag=0;
        Date date=new Date();
        for(StatisticsBean statisticsBean:planRegularCheckList){
            if (null==kpiStatisticsList){
                kpiStatisticsList=new ArrayList<>();
            }
            //先判断是否有对应员工的临时检查计划
            List<StatisticsBean> tempIrregularList=acutalIrregularCheckList.stream().filter(s->s.getCode().equals(statisticsBean.getCode())).collect(Collectors.toList());
            //由于数据问题，在统计时没有办法取到水司的名称，在此之前需要根据水司code获取水司名称
            CorpBean corpBean=factory.getMapper(CorpManagementMapper.class).get(statisticsBean.getCode());
            //水司不存在，结束本次循环
            if (null==corpBean){
                continue;
            }
            Float total=+Float.parseFloat(statisticsBean.getValue());
            if (null!=tempIrregularList&&tempIrregularList.size()>0){
                flag++;
                total=total+Float.parseFloat(tempIrregularList.get(0).getValue());
            }
            //确保分母不为0且大于0
            if (total>0){
                List<StatisticsBean> tempActualRegular=auctualRegularCheckList.stream().filter(s->s.getCode().equals(statisticsBean.getCode())).collect(Collectors.toList());
                Float result=0F;
                if (tempActualRegular!=null&&tempActualRegular.size()>0){
                    result=Float.parseFloat(tempActualRegular.get(0).getValue());
                }
                KpiStatistics kpiStatistics=generateKpiStatistics(kpiTemplate,type,startTime);
                kpiStatistics.setKpiValue(result/total);
                kpiStatistics.setObjectId(statisticsBean.getCode());
                kpiStatistics.setObjectName(corpBean.getCorpName());
                kpiStatistics.setStatisticalType(3);
                kpiStatistics.setAddTime(date);
                kpiStatisticsList.add(kpiStatistics);
            }
        }
        //临时检查计划的员工记录存在定期人员中没有的
        if (flag<acutalIrregularCheckList.size()){
            if (null==kpiStatisticsList){
                kpiStatisticsList=new ArrayList<>();
            }
            //获取定期的人员code
            List<String> userCodeList=planRegularCheckList.stream().map(StatisticsBean::getCode).collect(Collectors.toList());
            for(StatisticsBean statisticsBean:acutalIrregularCheckList){
                if (!userCodeList.contains(statisticsBean.getCode())){
                    //由于数据问题，在统计时没有办法取到水司的名称，在此之前需要根据水司code获取水司名称
                    CorpBean corpBean=factory.getMapper(CorpManagementMapper.class).get(statisticsBean.getCode());
                    //水司不存在，结束本次循环
                    if (null==corpBean){
                        continue;
                    }
                    List<StatisticsBean> tempActualRegular=auctualRegularCheckList.stream().filter(s->s.getCode().equals(statisticsBean.getCode())).collect(Collectors.toList());
                    KpiStatistics kpiStatistics=generateKpiStatistics(kpiTemplate,type,startTime);
                    kpiStatistics.setKpiValue(Float.parseFloat(tempActualRegular.get(0).getValue())/Float.parseFloat(statisticsBean.getValue()));
                    kpiStatistics.setObjectId(statisticsBean.getCode());
                    kpiStatistics.setObjectName(corpBean.getCorpName());
                    kpiStatistics.setStatisticalType(3);
                    kpiStatistics.setAddTime(date);
                    kpiStatisticsList.add(kpiStatistics);
                }
            }
        }
        //执行批量插入操作
        if (null!=kpiStatisticsList&&kpiStatisticsList.size()>0){
            Integer value=statisticsMapper.batchInsert(kpiStatisticsList);
            if(value<0){
                SimpleDateFormat format=new SimpleDateFormat();
                String a=type==2?getDateValue(type,startTime):format.format(startTime);
                throw  new Exception(a+"计算指标库code为0031，统计层级为水司失败");
            }
        }
    }

    /**
     * 统计层级为集团，指标名称：检查计划完成率，指标code为0031
     * @param type 日期类型，1代表是月份，2代表是季度，3代表是年
     * @param startTime 统计的开始时间
     * @param endTime 统计的结束时间
     */
    private void countPerformancePlanRateByDistrict(SessionFactory factory,Integer type,Date startTime,Date endTime) throws Exception {
        PerformMancePlanRateStatisticsMapper performMancePlanRateStatisticsMapper=factory.getMapper(PerformMancePlanRateStatisticsMapper.class);
        KpiStatisticsMapper statisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
        KPITemplate kpiTemplate=factory.getMapper(KPITemplateMapper.class).queryTemplateByCode("0031");
        List<KpiStatistics> kpiStatisticsList=null;
        Date date=new Date();
        List<District> districtList=factory.getMapper(DistrictMapper.class).queryAllDistrict(null,null);
        if(null!=districtList&&districtList.size()>0){
            for(District district:districtList){
                if (null==kpiStatisticsList){
                    kpiStatisticsList=new ArrayList<>();
                }
                List<DistrictCorpRelation> relationList=districtService.queryDistrictCorp(district.getCode(),null,null).getData().getList();
                List<String> corpCodeList=relationList.stream().map(DistrictCorpRelation::getCorpCode).collect(Collectors.toList());
                if (corpCodeList!=null&&corpCodeList.size()>0){
                    //查询集团统计值
                    Integer plan=performMancePlanRateStatisticsMapper.countPlanRegularCheckStatisticsByDistrict(startTime,endTime,null);
                    Integer actualRegular=performMancePlanRateStatisticsMapper.countActualRegularCheckStatisticsByDistrict(startTime,endTime,null);
                    Integer actualIrregular=performMancePlanRateStatisticsMapper.countActualIRRegularCheckStatisticsByDistrict(startTime,endTime,null);
                    Float total=Float.parseFloat(plan.toString())+Float.parseFloat(actualIrregular.toString());
                    //确保分母不为0
                    if (total>0){
                        //获取当前统计指标实体类
                        //获取当前统计指标实体类

                        KpiStatistics kpiStatistics=generateKpiStatistics(kpiTemplate,type,startTime);
                        kpiStatistics.setObjectId(district.getCode());
                        kpiStatistics.setObjectName(district.getName());
                        kpiStatistics.setKpiValue(Float.parseFloat(actualIrregular.toString())/Float.parseFloat(total.toString()));
                        kpiStatistics.setStatisticalType(4);
                        kpiStatistics.setAddTime(date);
                        kpiStatisticsList.add(kpiStatistics);
                    }
                }

            }
        }
        //执行批量插入操作
        if (null!=kpiStatisticsList&&kpiStatisticsList.size()>0){
            Integer value=statisticsMapper.batchInsert(kpiStatisticsList);
            if(value<0){
                SimpleDateFormat format=new SimpleDateFormat();
                String a=type==2?getDateValue(type,startTime):format.format(startTime);
                throw  new Exception(a+"计算指标库code为0031，统计层级为片区失败");
            }
        }
    }

    /**
     * 统计层级为集团，指标名称：检查计划完成率，指标code为0031
     * @param type 日期类型，1代表是月份，2代表是季度，3代表是年
     * @param startTime 统计的开始时间
     * @param endTime 统计的结束时间
     */
    private void countPerformancePlanRateByGroup(SessionFactory factory,Integer type,Date startTime,Date endTime) throws Exception {
        PerformMancePlanRateStatisticsMapper performMancePlanRateStatisticsMapper=factory.getMapper(PerformMancePlanRateStatisticsMapper.class);
        KpiStatisticsMapper statisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
        KPITemplate kpiTemplate=factory.getMapper(KPITemplateMapper.class).queryTemplateByCode("0031");
        List<KpiStatistics> kpiStatisticsList=null;
        Date date=new Date();
        //查询集团统计值
        Integer plan=performMancePlanRateStatisticsMapper.countPlanRegularCheckStatisticsByDeptOrGroup(startTime,endTime,null);
        Integer actualRegular=performMancePlanRateStatisticsMapper.countPlanRegularCheckStatisticsByDeptOrGroup(startTime,endTime,null);
        Integer actualIrregular=performMancePlanRateStatisticsMapper.countActualIRRegularCheckStatisticsByDeptOrGroup(startTime,endTime,null);
        Float total=Float.parseFloat(plan.toString())+Float.parseFloat(actualIrregular.toString());
        //确保分母不为0
        if (total>0){
            //获取当前统计指标实体类
            //获取当前统计指标实体类
            if (null==kpiStatisticsList){
                kpiStatisticsList=new ArrayList<>();
            }
            KpiStatistics kpiStatistics=generateKpiStatistics(kpiTemplate,type,startTime);
            kpiStatistics.setObjectId("c75d5edacbc042448dab01951208421b");
            kpiStatistics.setObjectName("粤海水资源");
            kpiStatistics.setKpiValue(Float.parseFloat(actualIrregular.toString())/Float.parseFloat(total.toString()));
            kpiStatistics.setStatisticalType(5);
            kpiStatistics.setAddTime(date);
            kpiStatisticsList.add(kpiStatistics);
        }
        //执行批量插入操作
        if (null!=kpiStatisticsList&&kpiStatisticsList.size()>0){
            Integer value=statisticsMapper.batchInsert(kpiStatisticsList);
            if(value<0){
                SimpleDateFormat format=new SimpleDateFormat();
                String a=type==2?getDateValue(type,startTime):format.format(startTime);
                throw  new Exception(a+"计算指标库code为0031，统计层级为集团失败");
            }
        }
    }
}
